﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using EyFramework.ORM;
using EyFramework.Sys.Core;
using ShuJuGj.Core.Dao;
using ShuJuGj.Entity;
using SqlSugar;

namespace ShuJuGj.Core.Service
{
    /// <summary>
    ///  SJGJ_SHUJUJI表的服务实现类
    /// </summary>
    public class SjgjShujujiService : BaseHisService, ISjgjShujujiService
    {
        protected readonly ISjgjShujujiDao _SjgjShujujiDao;

        public SjgjShujujiService(ISjgjShujujiDao sjgjShujujiDao)
        {
            _SjgjShujujiDao = sjgjShujujiDao;
        }

        /// <summary>
        /// 删除指定数据
        /// </summary>
        /// <param name="num">数据编号</param>
        /// <returns></returns>
        public bool delete(int num)
        {
            return _SjgjShujujiDao.Delete(num);
        }

        /// <summary>
        /// 编辑内容
        /// </summary>
        /// <param name="name">项目名称</param>
        /// <param name="zt">项目状态</param>
        /// <param name="num">项目位置</param>
        /// <returns></returns>
        public bool edit(string name, string zt, int num)
        {
            return _SjgjShujujiDao.edit(name, zt, num);
        }

        /// 根据表明获取表的字段信息
        /// </summary>
        /// <param name="connectType"></param>
        /// <param name="tbname"></param>
        /// <returns></returns>
        public List<ColumnInfo> GetColumnInfo(string connectType, string pTableName)
        {
            List<ColumnInfo> cols = new List<ColumnInfo>();
            if (connectType == "1")
            {
                string sql = "SELECT COLUMN_NAME,COLUMN_ID FROM ALL_TAB_COLS WHERE TABLE_NAME='{0}' ORDER BY COLUMN_ID";
                sql = string.Format(sql, pTableName);
                using (DataTable data = DbHelper.SelectTable(sql))
                {
                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        ColumnInfo col = new ColumnInfo(int.Parse(data.Rows[i]["COLUMN_ID"].ToString()), data.Rows[i]["COLUMN_NAME"].ToString());
                        cols.Add(col);
                    }
                }
            }
            else
            {
                string sql = "select name,colid from syscolumns where id=(select max(id) from sysobjects where upper(name)='{0}') order by colorder";
                sql = string.Format(sql, pTableName);
                using (DataTable data = TjDbHelper.SelectTable(sql))
                {
                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        ColumnInfo col = new ColumnInfo(int.Parse(data.Rows[i]["colid"].ToString()), data.Rows[i]["name"].ToString());
                        cols.Add(col);
                    }
                }
            }
            return cols;
        }

        public List<SjgjShujuji> GetListBy()
        {
            return _SjgjShujujiDao.GetListBy();
        }

        /// <summary>
        /// 修改用户状态
        /// </summary>
        /// <param name="sjgjShujuji"></param>
        /// <returns></returns>
        public bool updateStates(SjgjShujuji sjgjShujuji)
        {
            return _SjgjShujujiDao.updateStates(sjgjShujuji);
        }

        /// 根据任务类型获取数据集
        /// </summary>
        /// <param name="taskType"></param>
        /// <returns></returns>
        public List<SjgjShujuji> GetNeedUploadSjj(string taskType)
        {
            return _SjgjShujujiDao.GetListByTaskType(taskType);
        }

        public int GetTotRecord(SjgjShujuji sjj)
        {
            int tot = 0;
            if (sjj.CONNECT_TYPE == "2")
            {
                string sql = string.Format("SELECT COUNT(*) cont FROM {0} A WHERE not exists(select 1 from SJGJ_UPLOAD_DATA WHERE DATA_KEY= {1} AND TBNAME='{0}')", sjj.TBNAME, getDataKey(sjj.CONNECT_TYPE, sjj.WYBZ));
                using (DataTable data = TjDbHelper.SelectTable(sql))
                {
                    if (data.Rows.Count > 0)
                    {
                        tot = int.Parse(data.Rows[0]["cont"].ToString());
                    }
                }
            }
            else
            {
                string sql = string.Format("SELECT COUNT(*) cont FROM {0} A WHERE not exists(select 1 from SJGJ_UPLOAD_DATA WHERE DATA_KEY= {1} AND TBNAME='{0}')", sjj.TBNAME, getDataKey(sjj.CONNECT_TYPE, sjj.WYBZ));
                using (DataTable data = DbHelper.SelectTable(sql))
                {
                    if (data.Rows.Count > 0)
                    {
                        tot = int.Parse(data.Rows[0]["cont"].ToString());
                    }
                }
            }
            return tot;
        }

        public DataTable GetUploadData(SjgjShujuji sjj)
        {
            if (sjj.CONNECT_TYPE == "1")
            {
                string sql = string.Format("SELECT * FROM {0} A WHERE not exists(select 1 from SJGJ_UPLOAD_DATA WHERE DATA_KEY= {1} AND TBNAME='{0}')", sjj.TBNAME.ToUpper(), getDataKey(sjj.CONNECT_TYPE, sjj.WYBZ));
                return DbHelper.SelectTable(sql);
            }
            else
            {
                string sql = string.Format("SELECT * FROM {0} A WHERE not exists(select 1 from SJGJ_UPLOAD_DATA WHERE DATA_KEY= {1} AND TBNAME='{0}')", sjj.TBNAME.ToUpper(), getDataKey(sjj.CONNECT_TYPE, sjj.WYBZ));
                return TjDbHelper.SelectTable(sql);
            }
        }

        private string getDataKey(string connectType, string wybz)
        {
            string connetctStr = "";
            if (connectType == "1")
            {
                connetctStr = "||'^'||";
            }
            else
            {
                connetctStr = "+'^'+";
            }
            string whereConditon = "";
            string[] wybzkeys = wybz.Split(new char[] { '^' });
            for (int i = 0; i < wybzkeys.Length; i++)
            {
                if (string.IsNullOrEmpty(whereConditon))
                {
                    whereConditon = wybzkeys[i];
                }
                else
                {
                    whereConditon = whereConditon + connetctStr + wybzkeys[i];
                }
            }
            return whereConditon;
        }

        public void SaveUploadData(List<SjgjUploadData> data, SjgjShujuji sjj)
        {
            //如果非实时上传的数据集，都默认不保存上传成功的数据。要求数据集的试图保留昨天一天的数据即可，试图有数据就上传
            if (sjj.TASK_TYPE == "1")
            {
                return;
            }
            ////在这个命令行中,用到了参数,参数我们很熟悉,但是这个参数在传值的时候
            ////用到的是数组,而不是单个的值,这就是它独特的地方
            //string sql = "";
            ////在下面的循环中,先把数组定义好,而不是像上面那样直接生成SQL
            //for (int i = 0; i < data.Count; i++)
            //{
            //    sql = @"INSERT INTO SJGJ_UPLOAD_DATA (UPLOAD_DATE, TASK_ID,
            //                       BATCH_TASK_ID, SJJSEQ, TBNAME, YWMC,
            //                       DATA_KEY)
            //                    VALUES ({0},
            //                        '{1}',
            //                        '{2}',
            //                        '{3}',
            //                        '{4}',
            //                        '{5}',
            //                        '{6}')";

            //    if (sjj.CONNECT_TYPE == "1")
            //    {
            //        sql = string.Format(sql,
            //            "SYSDATE",
            //            data[i].TaskId,
            //            data[i].BatchTaskId,
            //            data[i].Sjjseq,
            //            data[i].Tbname,
            //            data[i].Ywmc,
            //            data[i].DataKey);
            //        DbHelper.ExecuteUpdate(sql);
            //    }
            //    else
            //    {
            //        sql = string.Format(sql,
            //            "GETDATE()",
            //            data[i].TaskId,
            //            data[i].BatchTaskId,
            //            data[i].Sjjseq,
            //            data[i].Tbname,
            //            data[i].Ywmc,
            //            data[i].DataKey);
            //        TjDbHelper.ExecuteUpdate(sql);
            //    }
            //}

            TjDbHelper.baseDaoTj.Db.Insertable(data).ExecuteCommand();
        }

        public SjgjShujuji GetShujuji(string vSeq)
        {
            return _SjgjShujujiDao.GetById(vSeq);
        }
    }
}